#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent):QMainWindow(parent),ui(new Ui::MainWindow) {
    ui->setupUi(this);

    //prepare margins
    ui->tabWidget->widget(0)->layout()->setSpacing(0);
    ui->tabWidget->widget(0)->layout()->setMargin(0);

    //prepare kernel tabs
    wKernel = new QWidget(ui->scrollArea);
    flKernel = new FlowLayout(wKernel);
    wKernel->setLayout(flKernel);
    ui->scrollArea->setWidget(wKernel);

    //load plugins
    loadPlugins();
}

MainWindow::~MainWindow() {
    delete ui;
}

bool MainWindow::loadPlugins() {
    //browse plugins directory
    QDir pluginsDir(qApp->applicationDirPath());
#if defined(Q_OS_WIN)
    if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
        pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
    if (pluginsDir.dirName() == "MacOS") {
        pluginsDir.cdUp();
        pluginsDir.cdUp();
        pluginsDir.cdUp();
    }
#endif
    pluginsDir.cd("Plugins");
    QString s;
    int i;
    QIcon icon;
    QList<float> matrix;
    foreach (QString fileName, pluginsDir.entryList(QDir::Files)) {
        QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName));
        QObject *plugin = pluginLoader.instance();
        if (plugin) {
            //check plugin again plugin types
            test = qobject_cast<MatrixPluginInterface *>(plugin);
            if (test) {

                s = test->version();
                i = test->matrixSize();
                icon = test->logo_small();
                PushButton *bt;
                bt = new PushButton();
                bt->plugin = (GenericPluginInterface*)plugin;
                bt->setObjectName(QString::fromUtf8("btOpen"));
                bt->setMaximumSize(QSize(40, 30));
                QStyle *style = QApplication::style();
                bt->setIcon(style->standardIcon(QStyle::SP_ComputerIcon));
                bt->setText(s);
                matrix = test->matrix();
                flKernel->addWidget(bt);

                //connects its left and right click
                connect(bt, SIGNAL(clicked()), this, SLOT(pluginClick()));
                connect(bt, SIGNAL(rightClicked()), this, SLOT(pluginRightClick()));
            }
        }
    }
    return true;
}

void MainWindow::pluginClick() {
    QMessageBox::information(this, "SAlut!", "Il clique à gauche", QMessageBox::Ok);
}

void MainWindow::pluginRightClick() {
    PushButton *emmiter = (PushButton*)sender();
    plugin = (GenericPluginInterface*)emmiter->plugin;
    PluginInfo *pi = new PluginInfo(this, plugin->logo_small(), plugin->logo_big(), plugin->name(), plugin->version(), plugin->description(), plugin->desc_image());
    pi->exec();
    delete pi;
}

